package com.ouyu.pdfprint.print_pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.ouyu.pdfprint.print_pdf.config.PdfProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;

@Slf4j
public class JavaToPdfHtmlFreeMarker {
    /**
     * 字体
     */
    private static  String FONT = "config/pdfTemplate/simhei.ttf";

    private static    String PATH = "/config/pdfTemplate";

    /**
     * 配置
     */
    private static Configuration freemarkerCfg = null;

    public JavaToPdfHtmlFreeMarker(PdfProperties pdfProperties) {
        freemarkerCfg = new Configuration();
        //freemarker的模板目录
        try {
//            freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath()));

            getUserDefinition(pdfProperties);

            freemarkerCfg.setClassForTemplateLoading(PathUtil.getCaller(),PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getUserDefinition(PdfProperties pdfProperties) {
        if(pdfProperties.getTemplatePath() != null){
            PATH = pdfProperties.getTemplatePath();
        }
        if(pdfProperties.getFont() != null){
            FONT = pdfProperties.getFont();
        }
    }

    static {
        freemarkerCfg = new Configuration();
        //freemarker的模板目录
        try {
//            freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath()));
            freemarkerCfg.setClassForTemplateLoading(PathUtil.getCaller(),"/config/pdfTemplate");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成pdf
     *
     * @param html    html文件路径
     * @param pdfName pdf文件路径
     * @param data    替换参数
     * @throws IOException
     * @throws DocumentException
     * @return PDF文件
     */
    public static void toPdf(String html, String pdfName, Map<String, Object> data) throws IOException, DocumentException {
        String content = JavaToPdfHtmlFreeMarker.freeMarkerRender(data, html);
        JavaToPdfHtmlFreeMarker.createPdf(content, pdfName);
    }

    /**
     * freemarker渲染html
     * @return 渲染结果
     */
    public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
        Writer out = new StringWriter();
        try {
            // 获取模板,并设置编码方式
            Template template = freemarkerCfg.getTemplate(htmlTmp);
            template.setEncoding("UTF-8");
            // 合并数据模型与模板，将合并后的数据和模板写入到流中，这里使用的字符流
            template.process(data, out);
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 生成PDF
     *
     * @param content 文本内容
     * @param pdfName pdf文件路径
     * @throws IOException
     * @throws DocumentException
     * @return PDF文件
     */
    public static void createPdf(String content, String pdfName) throws IOException, DocumentException {
        // step 1
        Document document = new Document(PageSize.A4);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfName));
        // step 3
        document.open();
        // step 4 //设置字体
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontImp.register(FONT);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"), fontImp);
        // step 5
        document.close();
    }

    /**
     * 添加pdf水印图片
     *
     * @param input     输入PDF
     * @param output    转出PDF
     * @param absoluteX 图片绝对X坐标
     * @param absoluteY 图片绝对Y坐标
     * @throws Exception
     */
    public static void addImage(String input, String output, Integer absoluteX, Integer absoluteY) throws Exception {
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(new File(output)));
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, out);
        int total = reader.getNumberOfPages();
        try {
            Image image = Image.getInstance("http://isr-dev.oss-cn-shenzhen.aliyuncs.com/1528164344767743775.png");
            image.setAbsolutePosition(absoluteX, absoluteY); // set the first background image of the absolute
            image.scaleToFit(120, 120);
            PdfContentByte content = stamper.getOverContent(1);// 在内容上方加水印
            content.addImage(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        stamper.close();
        reader.close();
    }
}
